package com.qiyun.dinghuohui.service;

import android.app.Service;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.qiyun.dinghuohui.ApplicationDataHolder;
import com.qiyun.dinghuohui.common.ClientCookie;
import com.qiyun.dinghuohui.common.CommonDataSets;
import com.qiyun.dinghuohui.utils.AsyncJsonTask;
import com.qiyun.dinghuohui.utils.DateUtil;
import com.qiyun.dinghuohui.utils.FileViewer;
import com.qiyun.dinghuohui.utils.JsonBuilder;
import com.qiyun.dinghuohui.utils.JsonParamInfoReturn;
import com.qiyun.dinghuohui.utils.LogDebug;
import com.qiyun.dinghuohui.utils.ResultListener;
import com.qiyun.dinghuohui.utils.ServerResponse;
import com.qiyun.dinghuohui.utils.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class ManagerService extends Service implements ResultListener {
    ApplicationDataHolder adh;
    private Timer mTimer = new Timer(true);
    private mTimerTask mTimerTaskTestLink;
    private final static String OP_SYNC_DATA = "sync_data";
    private int runcount = 0;
    private boolean bBusy = false;
    int time = 30;

    public class MainSyncBind extends Binder {
        public ManagerService getService() {
            return ManagerService.this;
        }
    }

    private MainSyncBind syncBind = new MainSyncBind();

    @Override
    public IBinder onBind(Intent arg0) {
        return syncBind;
    }

    private void DownBaseInfo() {
        if (ApplicationDataHolder.downloadPicForServer(ClientCookie.getServerUrl() + "/download/publicbasedata_o.gz",
                "publicbasedata_o.gz")) {
            ApplicationDataHolder.downloadPicForServer(ClientCookie.getServerUrl() + "/download/publicbasedata_g.gz",
                    "publicbasedata_g.gz");
            // 解压缩
            ApplicationDataHolder.GZipUnCompressFile(CommonDataSets.CLIENT_STRONGPATH
                    + "/publicbasedata_o.gz");
            ApplicationDataHolder.GZipUnCompressFile(CommonDataSets.CLIENT_STRONGPATH
                    + "/publicbasedata_g.gz");
            // 重新读取载入
            adh.readLocalBaseDataToReset();
            // 自动更新待同步的图片
            int goodsPicCount = 0;
            int curPicIndex = 0;
            String filename = "";
            String outfilename = "";
            String imageUrl = "";
            String codeTemp = "";
            String codeColorStr = "";
            String[] codeColors = new String[0];
            for (JSONObject jo : CommonDataSets.ds_pair.values()) {
                try {
                    codeTemp = jo.getString("pair_id");
                    if (jo.getInt("st") == 1 && jo.getInt("image_url") > 0) {
                        filename = codeTemp + ".jpg";
                        outfilename = "pair" + codeTemp + ".jpg";
                        imageUrl = ClientCookie.getServerUrl() + "/goods/pair/" + filename;
                        if (ApplicationDataHolder.downloadPicForServer(imageUrl, outfilename)) {
                            ApplicationDataHolder.getLoacalBitmapClear(outfilename);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            for (JSONObject jo : CommonDataSets.ds_goods) {
                try {
                    if (jo.getInt("picu") == 1) {
                        goodsPicCount = jo.getInt("image_url");
                        codeTemp = jo.getString("code");
                        codeColorStr = jo.getString("color_string");
                        curPicIndex = 0;
                        if (goodsPicCount > 0) {
                            if (CommonDataSets.ds_config_activity.picModal == 0) { // 编号+序号
                                for (int j = 0; j < goodsPicCount; j++) {
                                    if (j == 0) {
                                        filename = codeTemp + ".jpg";
                                        outfilename = codeTemp + ".jpg";
                                    } else {
                                        filename = codeTemp + "#"
                                                + String.valueOf(j + 1)
                                                + ".jpg";
                                        outfilename = codeTemp + "#"
                                                + String.valueOf(j + 1)
                                                + ".jpg";
                                    }
                                    imageUrl = ClientCookie.getServerUrl()
                                            + "/goods/img/" + filename;
                                    if (ApplicationDataHolder.downloadPicForServer(imageUrl, outfilename)) {
                                        ApplicationDataHolder.getLoacalBitmapClear(outfilename);
                                    }
                                }
                            } else if (CommonDataSets.ds_config_activity.picModal == 2) { // 编号+颜色
                                filename = codeTemp + ".jpg";
                                outfilename = codeTemp + ".jpg";
                                imageUrl = ClientCookie.getServerUrl()
                                        + "/goods/img/" + filename;
                                if (ApplicationDataHolder.downloadPicForServer(imageUrl, outfilename)) {
                                    ApplicationDataHolder.getLoacalBitmapClear(outfilename);
                                }
                                codeColors = codeColorStr.split(",");
                                for (String sc : codeColors) {
                                    filename = codeTemp + "#" + sc + ".jpg";
                                    outfilename = codeTemp + "#" + sc + ".jpg";
                                    imageUrl = ClientCookie.getServerUrl()
                                            + "/goods/img/" + filename;
                                    if (ApplicationDataHolder.downloadPicForServer(imageUrl, outfilename)) {
                                        ApplicationDataHolder.getLoacalBitmapClear(outfilename);
                                    }
                                }
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        adh = (ApplicationDataHolder) getApplication();
        mTimerTaskTestLink = new mTimerTask();
        mTimer.schedule(mTimerTaskTestLink, 1000, 1000 * time); // 30秒(1分钟)检测一次
    }

    private class mTimerTask extends TimerTask {

        @Override
        public void run() {
            if (!bBusy) {
                bBusy = true;
                // adh.restrarRegisterBatteryReceiver();
                // 定时同步数据（从服务上同步数据文件，并把本机的数据上传上去），要判断网络情况
                // 判断是否在同步时间内
                if (adh.isLogin() && adh.isCanReadRefrushBackData()) {// 登录成功后才自动同步
                    // FileViewer.appendMethod(adh.getLogFile(),
                    // "=====  login and CanReadRefrushBackData ====");
                    Date downloadDate = DateUtil.addMinutesToDate(adh.getFileUpdateHandleLastDate(), 5);
                    if (adh.isSaveOrderRealTime()) {// 如果是实时的,则5分钟同步一次基础数据
                        runcount++;
                        if (runcount >= 5) {
                            // FileViewer.appendMethod(adh.getLogFile(),
                            // "=====  realtime  ====");
                            // 下载 公用基础文件 文件名 publicbasedata.txt.gz
                            adh.CheckNetworkActivity();
                            if (adh.isOnline() && CommonDataSets.ds_config_activity.clientautobase) {
                                // 在线，则进行通讯
                                if (adh.downloadBaseInfo) {
                                    if (DateUtil.compareDatesAll(new Date(), downloadDate) != -1) {
                                        DownBaseInfo();
                                    }
                                }
                            }
                            runcount = 0;
                        }
                    } else {// 非实时,则要进行WIFI控制
                        // 判断是否需要同步
                        if (time != 5 && CommonDataSets.ds_config_activity.netOpenMinute == 1000) {
                            mTimer.cancel();
                            mTimer = new Timer(true);
                            time = 5;
                            mTimer.schedule(new mTimerTask(), 1000, 1000 * time);
                        } else if (time != 5 && CommonDataSets.ds_config_activity.netOpenMinute == 2000) {
                            mTimer.cancel();
                            mTimer = new Timer(true);
                            time = 10;
                            mTimer.schedule(new mTimerTask(), 1000, 1000 * time);
                        }
                        Date syncDate = DateUtil.addMinutesToDate(
                                adh.saveOrderBeginTime,
                                CommonDataSets.ds_config_activity.netOpenMinute);
                        Log.d("",
                                "syncDate->"
                                        + DateUtil
                                        .convertDateToString(
                                                DateUtil.DATE_FORMAT_YYYYMMDDHHMMSS,
                                                syncDate)
                                        + "  curDate->"
                                        + DateUtil
                                        .convertDateToString(
                                                DateUtil.DATE_FORMAT_YYYYMMDDHHMMSS,
                                                new Date())
                                        + "  saveOrderCalcTime->"
                                        + adh.saveOrderCalcTime
                                        + "  compareDatesAll->"
                                        + DateUtil.compareDatesAll(
                                        new Date(), syncDate));
                        // Date
                        // syncDate=DateUtil.addMinutesToDate(adh.saveOrderBeginTime,
                        // CommonDataSets.ds_config_activity.netOpenMinute);
                        if (adh.saveOrderCalcTime) {
                            if (DateUtil.compareDatesAll(new Date(),
                                    syncDate) != -1) { // 需要同步
                                adh.saveOrderBeginTime = new Date();
                                // FileViewer.appendMethod(adh.getLogFile(),
                                // "========= time at sync  ============");
                                adh.getWifiAdminOpen();
                                // 判断当前wifi状态
                                int waittimecount = 0;
                                while (adh.getWifiAdmin().checkState() != WifiManager.WIFI_STATE_ENABLED) {
                                    try {
                                        Thread.sleep(1000);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    waittimecount++;
                                    if (waittimecount > 50) {
                                        FileViewer.appendMethod(adh.getLogFile(),
                                                "========= open wifi timeout ============");
                                        break;
                                    }
                                }
                                if (adh.getWifiAdmin().checkState() == WifiManager.WIFI_STATE_ENABLED) {
                                    // 连接网络 获得连接的网络
                                    // adh.checkConnNet();
                                    Utils.checkHaveIpAddress(adh);
                                    /*
                                     * waittimecount=0; while (true){
									 * adh.setOnline
									 * (adh.getWifiAdmin().getIPAddress
									 * ()>0); if (adh.isOnline()){ break; }
									 * waittimecount++; if
									 * (waittimecount>60){
									 * adh.wifiLastSsid=""; break; } try {
									 * Thread.sleep(1000); } catch
									 * (InterruptedException e) {
									 * e.printStackTrace(); } }
									 */
                                    if (adh.downloadBaseInfo) {
                                        if (DateUtil.compareDatesAll(
                                                new Date(), downloadDate) != -1) {
                                            DownBaseInfo();
                                        }
                                    }
                                    checkDataNeedSync();
                                    /*
                                     * //adh.setOnline(adh.getWifiAdmin().
									 * getIPAddress()>0); if
									 * (adh.isOnline()){ //if
									 * (!adh.checkNetInList()){ //
									 * adh.checkConnNet(); //} //下载 公用基础文件
									 * 文件名 publicbasedata.txt.gz
									 * 
									 * }else{ failProcess(); }
									 */
                                } else {
                                    failProcess();
                                }
                            } else {
                                // 还没有到同步的时间
                            }
                        }
                    }
                }
                bBusy = false;
            }


        }

    }

    private void checkDataNeedSync() {
        // TODO:提交数据，判断有哪些数据未提交进行提交
        // 同步数据
        // 订单及标记都实时保存
        try {
            JSONArray notsyncdata_flag = CommonDataSets.getGoodsFlagNotSync();
            JSONArray notsyncdata_order = CommonDataSets.getOrderNotSync(adh.getUsername());
            JSONArray notsyncdata_display = CommonDataSets
                    .getGoodsDisplayFlagNotSync();
            if (notsyncdata_flag.length() > 0 || notsyncdata_order.length() > 0
                    || notsyncdata_display.length() > 0) {
                // 有数据需要同步先
                // 需要进行同步
                JSONObject postData = null;
                JsonBuilder jb = new JsonBuilder();
                JSONObject json = new JSONObject();
                try {
                    json.put("data_flag", notsyncdata_flag);
                    json.put("data_order", notsyncdata_order);
                    json.put("data_display", notsyncdata_display);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                postData = jb.setUsername(adh.getUsername())
                        .setOp(OP_SYNC_DATA).setDeviceId(adh.getDeviceId())
                        .setBattery(adh.getBattery()).setPostData(json)
                        .buildJson();
                new AsyncJsonTask(adh.getServerUrl(true, 0, "B"),
                        "/client/commonClientAction!syncdata",
                        ManagerService.this).execute(postData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPostDataComplete(ServerResponse response) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onPostDataError(ServerResponse response) {
        // 提交失败
		/*
		 * FileViewer.appendMethod(getLogFile(),
		 * "========= sync onPostDataError  ============");
		 * 
		 * adh.saveOrderFailCount=adh.saveOrderFailCount+1; if
		 * (adh.saveOrderFaileCountTip()){ //超过失败次数,进行提示
		 * adh.wifiAdmin.openWifi(); adh.setCanReadRefrushBackData(false);
		 * FileViewer.appendMethod(getLogFile(),
		 * "========= sync fail saveOrderFaileCountTip jump->MainSyncFailureActivity  ============"
		 * ); adh.saveOrderFaileCountTipShowActivity(); }else{
		 * adh.wifiAdmin.lastSsid=""; }
		 */
    }

    ;

    @Override
    public void onPostDataStart() {
        // TODO Auto-generated method stub

    }

    private void failProcess() {
        adh.saveOrderFailCount = adh.saveOrderFailCount + 1;
        FileViewer.appendMethod(adh.getLogFile(),
                "========= sync fail  ============  saveOrderFailCount="
                        + adh.saveOrderFailCount);
        if (adh.saveOrderFaileCountTip()) {
            // 超过失败次数,进行提示
            // adh.getWifiAdminOpen();
            FileViewer
                    .appendMethod(
                            adh.getLogFile(),
                            "========= sync fail saveOrderFaileCountTip jump->MainSyncFailureActivity  ============");
            adh.setCanReadRefrushBackData(false);
            adh.saveOrderFaileCountTipShowActivity();
        } else {
            adh.wifiLastSsid = "";
        }
    }

    @Override
    public void onPostDataSuccess(ServerResponse response) {
        JsonParamInfoReturn jsonParamInfoReturn = ApplicationDataHolder.paramCheckByReturn(response);
        if (!jsonParamInfoReturn.isParam_aliay()) {
            // 更新失败
            failProcess();
        } else {
            adh.saveOrderFailCount = 0;
            // FileViewer.appendMethod(adh.getLogFile(),
            // "========= sync succ  ============");
            CommonDataSets.userDataClearSync(adh.getUsername(), true);// 同步完成后，更改标记
            CommonDataSets.saveUserDataToDisk();
            adh.wifiSaveNetId();
            if (CommonDataSets.ds_config_activity.netOpen) {
                adh.getWifiAdminClose();
            }
            adh.saveOrderFlagEnabled(false);
            try {
                adh.CheckOffLine(jsonParamInfoReturn.getParam_json().getString("oldmac"));
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
        }
    }

    @Override
    public void setProgressMessage(String message) {
        // TODO Auto-generated method stub

    }

}
